<template>
  <div class="merchant-dashboard">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h2>商户数据统计</h2>
    </div>

    <!-- 数据概览卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-header">
          <i class="el-icon-shopping-cart-full stat-icon"></i>
          <div class="stat-title">本月订单</div>
        </div>
        <div class="stat-value">
          <count-to :startVal="0" :endVal="dashboardData.orderCount" :duration="2000">
          </count-to>
        </div>
        <div class="stat-footer">
          较上月
          <span :class="dashboardData.orderGrowth >= 0 ? 'up' : 'down'">
            {{ dashboardData.orderGrowth >= 0 ? '+' : '' }}{{ dashboardData.orderGrowth }}%
            <i :class="dashboardData.orderGrowth >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
          </span>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-header">
          <i class="el-icon-money stat-icon"></i>
          <div class="stat-title">本月销售额</div>
        </div>
        <div class="stat-value">
          ¥<count-to :startVal="0" :endVal="dashboardData.salesAmount" :duration="2000" :decimals="2">
          </count-to>
        </div>
        <div class="stat-footer">
          较上月
          <span :class="dashboardData.salesGrowth >= 0 ? 'up' : 'down'">
            {{ dashboardData.salesGrowth >= 0 ? '+' : '' }}{{ dashboardData.salesGrowth }}%
            <i :class="dashboardData.salesGrowth >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
          </span>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-header">
          <i class="el-icon-s-goods stat-icon"></i>
          <div class="stat-title">商品总数</div>
        </div>
        <div class="stat-value">
          <count-to :startVal="0" :endVal="dashboardData.productCount" :duration="2000">
          </count-to>
        </div>
        <div class="stat-footer">
          上架商品
          <span class="highlight">{{ dashboardData.activeProductCount }}</span>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-header">
          <i class="el-icon-star-on stat-icon"></i>
          <div class="stat-title">平均评分</div>
        </div>
        <div class="stat-value">
          <count-to :startVal="0" :endVal="dashboardData.avgRating" :duration="2000" :decimals="1">
          </count-to>
        </div>
        <div class="stat-footer">
          共 <span class="highlight">{{ dashboardData.reviewCount }}</span> 条评价
        </div>
      </el-card>
    </div>

    <div class="content-wrapper">
      <!-- 销售趋势图表 -->
      <el-card class="chart-card" shadow="hover">
        <div slot="header" class="chart-header">
          <span>销售趋势</span>
          <el-radio-group v-model="salesChartPeriod" size="mini" @change="fetchSalesTrend">
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="year">全年</el-radio-button>
          </el-radio-group>
        </div>
        <div class="chart-content">
          <div ref="salesTrendChart" class="chart"></div>
        </div>
      </el-card>

      <!-- 订单状态分布图表 -->
      <el-card class="chart-card" shadow="hover">
        <div slot="header" class="chart-header">
          <span>订单状态分布</span>
          <el-button type="text" @click="fetchOrderStatusDistribution">刷新</el-button>
        </div>
        <div class="chart-content">
          <div ref="orderStatusChart" class="chart"></div>
        </div>
      </el-card>
    </div>

    <div class="content-wrapper">
      <!-- 热销商品TOP5图表 -->
      <el-card class="chart-card" shadow="hover">
        <div slot="header" class="chart-header">
          <span>热销商品 TOP5</span>
          <el-button type="text" @click="fetchTopProducts">刷新</el-button>
        </div>
        <div class="chart-content">
          <div ref="topProductsChart" class="chart"></div>
        </div>
      </el-card>

      <!-- 商户统计指标 -->
      <el-card class="metrics-card" shadow="hover">
        <div slot="header" class="metrics-header">
          <span>经营指标</span>
          <el-button type="text" @click="fetchMerchantMetrics">刷新</el-button>
        </div>
        <div class="metrics-content">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="metric-item">
                <div class="metric-title">退货率</div>
                <div class="metric-value">{{ metrics.refundRate }}%</div>
                <el-progress 
                  :percentage="metrics.refundRate" 
                  :color="getRefundRateColor(metrics.refundRate)" 
                  :format="() => ''" 
                  :stroke-width="8">
                </el-progress>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="metric-item">
                <div class="metric-title">客单价</div>
                <div class="metric-value">¥{{ metrics.avgOrderValue.toFixed(2) }}</div>
                <div class="metric-desc">平均订单金额</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="metric-item">
                <div class="metric-title">复购率</div>
                <div class="metric-value">{{ metrics.repurchaseRate }}%</div>
                <el-progress 
                  :percentage="metrics.repurchaseRate" 
                  :color="'#67C23A'" 
                  :format="() => ''" 
                  :stroke-width="8">
                </el-progress>
              </div>
            </el-col>
          </el-row>
          
          <div class="rating-distribution">
            <div class="rating-title">评分分布</div>
            <div class="rating-chart">
              <div ref="ratingDistributionChart" class="rating-chart-container"></div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 最新订单列表 -->
    <el-card class="latest-orders-card" shadow="hover">
      <div slot="header" class="latest-orders-header">
        <span>最新订单</span>
        <el-button type="text" @click="goToPage('/order-manager')">查看全部</el-button>
      </div>
      <div class="latest-orders-content">
        <el-table :data="latestOrders" border style="width: 100%" size="small">
          <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
          <el-table-column label="商品信息" min-width="300">
            <template slot-scope="scope">
              <div class="product-info">
                <el-image :src="'api'+scope.row.product.imageUrl" fit="cover" style="width: 40px; height: 40px">
                </el-image>
                <div class="product-detail">
                  <div class="product-name">{{ scope.row.product.name }}</div>
                  <div class="product-price">
                    ¥{{ scope.row.price.toFixed(2) }} × {{ scope.row.quantity }}
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" label="订单金额" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.totalPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" width="120">
            <template slot-scope="scope">
              <el-tag :type="getOrderStatusType(scope.row.status)">
                {{ orderStatusMap[scope.row.status] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="下单时间" width="180">
            <template slot-scope="scope">
              {{ formatTime(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleOrderDetail(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import Request from '@/utils/request'
import CountTo from 'vue-count-to'
import { formatTime } from '@/utils/time'
import * as echarts from 'echarts'

export default {
  name: 'MerchantDashboard',
  components: {
    CountTo
  },
  inject: ['userInfo'],
  data() {
    return {
      // 统计数据
      dashboardData: {
        orderCount: 0,
        orderGrowth: 0,
        salesAmount: 0,
        salesGrowth: 0,
        productCount: 0,
        activeProductCount: 0,
        avgRating: 0,
        reviewCount: 0,
      },
      // 图表相关
      salesTrendChart: null,
      orderStatusChart: null,
      topProductsChart: null,
      ratingDistributionChart: null,
      salesChartPeriod: 'month',
      salesTrendData: {
        dates: [],
        sales: []
      },
      orderStatusData: [],
      topProducts: [],
      // 经营指标数据
      metrics: {
        refundRate: 0,
        avgOrderValue: 0,
        repurchaseRate: 0,
        ratingDistribution: []
      },
      // 最新订单
      latestOrders: [],
      // 订单状态映射
      orderStatusMap: {
        0: '待支付',
        1: '已支付',
        2: '已发货',
        3: '已完成',
        4: '已取消',
        5: '已退款'
      }
    }
  },
  created() {
    this.fetchDashboardData()
    this.fetchLatestOrders()
    this.fetchMerchantMetrics()
  },
  mounted() {
    this.initCharts()
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    if (this.salesTrendChart) {
      this.salesTrendChart.dispose()
    }
    if (this.orderStatusChart) {
      this.orderStatusChart.dispose()
    }
    if (this.topProductsChart) {
      this.topProductsChart.dispose()
    }
    if (this.ratingDistributionChart) {
      this.ratingDistributionChart.dispose()
    }
    window.removeEventListener('resize', this.resizeCharts)
  },
  methods: {
    // 获取仪表盘数据
    async fetchDashboardData() {
      try {
        const res = await Request.get('/merchant/dashboard', {
          params: {
            merchantId: this.userInfo.id
          }
        })
        if (res.code === '0') {
          this.dashboardData = res.data
        }
      } catch (error) {
        console.error('获取仪表盘数据失败:', error)
        this.$message.error('获取仪表盘数据失败')
      }
      
      // 获取各图表数据
      this.fetchSalesTrend()
      this.fetchOrderStatusDistribution()
      this.fetchTopProducts()
    },
    
    // 获取销售趋势
    async fetchSalesTrend() {
      try {
        const res = await Request.get('/merchant/sales/trend', {
          params: {
            merchantId: this.userInfo.id,
            period: this.salesChartPeriod
          }
        })
        if (res.code === '0') {
          console.log('获取到的销售趋势数据:', res.data);
          this.salesTrendData = res.data;
          this.$nextTick(() => {
            this.updateSalesTrendChart();
          });
        }
      } catch (error) {
        console.error('获取销售趋势数据失败:', error);
        this.$message.error('获取销售趋势数据失败');
      }
    },
    
    // 获取订单状态分布
    async fetchOrderStatusDistribution() {
      try {
        const res = await Request.get('/merchant/orders/status-distribution', {
          params: {
            merchantId: this.userInfo.id
          }
        })
        if (res.code === '0') {
          this.orderStatusData = res.data
          this.updateOrderStatusChart()
        }
      } catch (error) {
        console.error('获取订单状态分布数据失败:', error)
      }
    },
    
    // 获取热销商品
    async fetchTopProducts() {
      try {
        const res = await Request.get('/merchant/products/top', {
          params: {
            merchantId: this.userInfo.id,
            limit: 5
          }
        })
        if (res.code === '0') {
          this.topProducts = res.data
          this.updateTopProductsChart()
        }
      } catch (error) {
        console.error('获取热销商品数据失败:', error)
      }
    },
    
    // 获取商户统计指标
    async fetchMerchantMetrics() {
      try {
        const res = await Request.get('/merchant/metrics', {
          params: {
            merchantId: this.userInfo.id
          }
        })
        if (res.code === '0') {
          this.metrics = res.data
          this.$nextTick(() => {
            this.updateRatingDistributionChart()
          })
        }
      } catch (error) {
        console.error('获取商户统计指标失败:', error)
      }
    },
    
    // 获取最新订单
    async fetchLatestOrders() {
      try {
        const res = await Request.get('/order/page', {
          params: {
            merchantId: this.userInfo.id,
            currentPage: 1,
            size: 5
          }
        })
        if (res.code === '0') {
          this.latestOrders = res.data.records
        }
      } catch (error) {
        console.error('获取最新订单失败:', error)
      }
    },
    
    // 初始化图表
    initCharts() {
      this.$nextTick(() => {
        this.salesTrendChart = echarts.init(this.$refs.salesTrendChart)
        this.orderStatusChart = echarts.init(this.$refs.orderStatusChart)
        this.topProductsChart = echarts.init(this.$refs.topProductsChart)
        this.ratingDistributionChart = echarts.init(this.$refs.ratingDistributionChart)
        
        this.fetchSalesTrend()
        this.fetchOrderStatusDistribution()
        this.fetchTopProducts()
        this.updateRatingDistributionChart()
      })
    },
    
    // 更新销售趋势图表
    updateSalesTrendChart() {
      if (!this.salesTrendChart) {
        console.warn('销售趋势图表未初始化');
        return;
      }
      
      // 确保数据存在且有效
      if (!this.salesTrendData || !this.salesTrendData.dates || !this.salesTrendData.sales) {
        console.warn('销售趋势数据无效:', this.salesTrendData);
        // 显示空数据
        this.salesTrendChart.setOption({
          tooltip: {
            trigger: 'axis',
            formatter: '{b}<br/>销售额: ¥{c}'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '¥{value}'
            }
          },
          series: [
            {
              name: '销售额',
              type: 'line',
              smooth: true,
              data: [],
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(58,77,233,0.3)' },
                  { offset: 1, color: 'rgba(58,77,233,0.1)' }
                ])
              },
              itemStyle: {
                color: '#3a4de9'
              },
              lineStyle: {
                width: 2
              }
            }
          ]
        });
        return;
      }
      
      console.log('设置销售趋势图表数据:', this.salesTrendData.dates, this.salesTrendData.sales);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>销售额: ¥{c}'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.salesTrendData.dates || []
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        series: [
          {
            name: '销售额',
            type: 'line',
            smooth: true,
            data: this.salesTrendData.sales || [],
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(58,77,233,0.3)' },
                { offset: 1, color: 'rgba(58,77,233,0.1)' }
              ])
            },
            itemStyle: {
              color: '#3a4de9'
            },
            lineStyle: {
              width: 2
            }
          }
        ]
      }
      
      this.salesTrendChart.setOption(option);
    },
    
    // 更新订单状态分布图表
    updateOrderStatusChart() {
      if (!this.orderStatusChart) return
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          formatter: name => {
            const item = this.orderStatusData.find(item => item.name === name)
            return `${name}: ${item ? item.value : 0}`
          }
        },
        series: [
          {
            name: '订单状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.orderStatusData || []
          }
        ],
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#36CBCB']
      }
      
      this.orderStatusChart.setOption(option)
    },
    
    // 更新热销商品图表
    updateTopProductsChart() {
      if (!this.topProductsChart) return
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}: {c}件'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          axisLabel: {
            formatter: (value) => value + '件'
          }
        },
        yAxis: {
          type: 'category',
          data: this.topProducts.map(item => item.name).reverse(),
          axisLabel: {
            formatter: (value) => {
              if (value.length > 10) {
                return value.substring(0, 10) + '...'
              }
              return value
            }
          }
        },
        series: [{
          name: '销售数量',
          type: 'bar',
          data: this.topProducts.map(item => item.salesCount).reverse(),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#2378f7' },
                { offset: 0.7, color: '#2378f7' },
                { offset: 1, color: '#83bff6' }
              ])
            }
          }
        }]
      }
      
      this.topProductsChart.setOption(option)
    },
    
    // 更新评分分布图表
    updateRatingDistributionChart() {
      if (!this.ratingDistributionChart || !this.metrics.ratingDistribution) return
      
      const ratingLabels = ['1星', '2星', '3星', '4星', '5星']
      const ratingValues = this.metrics.ratingDistribution.map(item => item.count)
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}条评价'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ratingLabels
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: ratingValues,
          type: 'bar',
          itemStyle: {
            color: (params) => {
              const colors = ['#F56C6C', '#E6A23C', '#909399', '#67C23A', '#409EFF']
              return colors[params.dataIndex]
            }
          },
          label: {
            show: true,
            position: 'top'
          }
        }]
      }
      
      this.ratingDistributionChart.setOption(option)
    },
    
    // 调整图表大小
    resizeCharts() {
      if (this.salesTrendChart) {
        this.salesTrendChart.resize()
      }
      if (this.orderStatusChart) {
        this.orderStatusChart.resize()
      }
      if (this.topProductsChart) {
        this.topProductsChart.resize()
      }
      if (this.ratingDistributionChart) {
        this.ratingDistributionChart.resize()
      }
    },
    
    // 获取退货率颜色
    getRefundRateColor(rate) {
      if (rate < 5) return '#67C23A'
      if (rate < 10) return '#E6A23C'
      return '#F56C6C'
    },
    
    // 获取订单状态类型
    getOrderStatusType(status) {
      const typeMap = {
        0: 'warning',   // 待支付
        1: 'primary',   // 已支付
        2: 'success',   // 已发货
        3: 'info',      // 已完成
        4: 'danger',    // 已取消
        5: 'info'       // 已退款
      }
      return typeMap[status] || 'info'
    },
    
    // 跳转到指定页面
    goToPage(path, query = {}) {
      this.$router.push({
        path,
        query
      })
    },
    
    // 查看订单详情
    handleOrderDetail(order) {
      this.$router.push(`/order-detail/${order.id}`)
    },
    
    // 格式化时间
    formatTime
  }
}
</script>

<style lang="less" scoped>
.merchant-dashboard {
  padding: 24px;
  background-color: #fff8f0;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 24px;

  h2 {
    font-size: 24px;
    font-weight: 500;
    color: #E67E22;
    margin: 0;
  }
}

.stat-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 24px;

  .stat-card {
    flex: 1;
    min-width: 200px;
    background-color: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);

    .stat-header {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
    }

    .stat-icon {
      font-size: 24px;
      margin-right: 12px;
      color: #F39C12;
      background-color: rgba(243, 156, 18, 0.1);
      width: 40px;
      height: 40px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .stat-title {
      font-size: 16px;
      color: #909399;
    }

    .stat-value {
      font-size: 28px;
      font-weight: bold;
      color: #E67E22;
      margin-bottom: 16px;
    }

    .stat-footer {
      font-size: 14px;
      color: #909399;

      .up {
        color: #46982a;
      }

      .down {
        color: #f56c6c;
      }

      .highlight {
        color: #F39C12;
        font-weight: 500;
      }
    }
  }
}

.content-wrapper {
  display: flex;
  gap: 20px;
  margin-bottom: 24px;

  @media (max-width: 1200px) {
    flex-direction: column;
  }

  .chart-card, .metrics-card {
    flex: 1;
    min-width: 300px;
    background-color: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  }
}

.chart-header, .metrics-header, .latest-orders-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #E67E22;
  margin-bottom: 20px;
}

.chart-content {
  height: 300px;

  .chart {
    width: 100%;
    height: 100%;
  }
}

.metrics-content {
  padding: 16px 0;

  .metric-item {
    background-color: #fff4e0;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;

    .metric-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }

    .metric-value {
      font-size: 24px;
      font-weight: bold;
      color: #E67E22;
      margin-bottom: 8px;
    }

    .metric-desc {
      font-size: 12px;
      color: #909399;
      margin-top: 8px;
    }
  }

  .rating-distribution {
    margin-top: 16px;

    .rating-title {
      font-size: 16px;
      color: #E67E22;
      margin-bottom: 16px;
    }

    .rating-chart {
      height: 200px;

      .rating-chart-container {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.latest-orders-card {
  margin-bottom: 24px;
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-size: 14px;
  color: #E67E22;
}

.product-price {
  font-size: 13px;
  color: #909399;
}
</style> 